<template>
  <view class="container">
    <view class="upload-btn">
      <button @click="chooseImages">选择图片</button>
      <button @click="uploadImages" :disabled="images.length === 0">
        上传图片
      </button>
    </view>

    <view class="image-list" v-if="images.length > 0">
      <view class="image-item" v-for="(img, index) in images" :key="index">
        <image :src="img.path" mode="aspectFill" @click="previewImage(index)" />
        <button @click="removeImage(index)">删除</button>
      </view>
    </view>

    <view v-if="uploadedUrls.length > 0" class="uploaded-list">
      <text>上传成功的URL：</text>
      <view v-for="(url, idx) in uploadedUrls" :key="idx">{{ url }}</view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from "vue";

interface ImageItem {
  path: string;
}

const images = ref<ImageItem[]>([]);
const uploadedUrls = ref<string[]>([]);

/** 选择图片 */
const chooseImages = () => {
  uni.chooseImage({
    count: 9, // 最大选择数量
    success: (res) => {
      const selected = res.tempFilePaths.map((p) => ({ path: p }));
      images.value.push(...selected);
    },
  });
};

/** 删除图片 */
const removeImage = (index: number) => {
  images.value.splice(index, 1);
};

/** 预览图片 */
const previewImage = (index: number) => {
  uni.previewImage({
    urls: images.value.map((i) => i.path),
    current: images.value[index].path,
  });
};

/** 上传图片 */
const uploadImages = async () => {
  uploadedUrls.value = [];
  for (const img of images.value) {
    const res = await new Promise<string>((resolve, reject) => {
      uni.uploadFile({
        url: "http://localhost:8089/wx/upload/files",
        filePath: img.path,
        name: "files",
        success: (uploadRes) => {
          const data = JSON.parse(uploadRes.data);
          if (data.code === "200") {
            resolve(data.data[0]);
          } else {
            reject(data.msg);
          }
        },
        fail: (err) => reject(err),
      });
    });
    uploadedUrls.value.push(res);
    console.log("上传成功的文件 URL:", res);
    const match = res.match(/images\/.+$/);
    const fileKey = match ? match[0] : "";
    console.log(fileKey);
  }
  uni.showToast({
    title: "上传完成",
    icon: "success",
  });
};
</script>

<style scoped>
.container {
  padding: 20px;
}
.upload-btn button {
  margin-right: 10px;
}
.image-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}
.image-item {
  position: relative;
  margin: 5px;
}
.image-item image {
  width: 100px;
  height: 100px;
  border-radius: 5px;
}
.image-item button {
  position: absolute;
  top: 0;
  right: 0;
  padding: 2px 5px;
  font-size: 12px;
}
.uploaded-list {
  margin-top: 20px;
}
</style>
